package cn.edu.cdp.dumpling.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;

@RestController
//@CrossOrigin
@RequestMapping("/images")
public class ImageController {
    @Value("${dumpling.dish}")
    private String dishPath;
    @Value("${dumpling.profiler}")
    private String profilerPath;
    @Value("${dumpling.business}")
    private String businessPath;

    private static final String DISH = "dish";
    private static final String PROFILER = "profiler";
    private static final String BUSINESS = "business";


    @GetMapping("/{dir}/{file_name}")
    public void profilerDownload(@PathVariable String dir, @PathVariable String file_name, HttpServletResponse response) {
        String path;
        switch (dir) {
            case DISH -> path = dishPath + file_name;
            case PROFILER -> path = profilerPath + file_name;
            case BUSINESS -> path = businessPath + file_name;
            default -> {
                return;     // 不符合的请求资源，直接return
            }
        }
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(path);
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
//            response.setContentType("application/octet-stream");  // 这种方式会下载图片
            response.setContentType("image/jpeg");

            int len;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
